﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharpShare.Utilities;

namespace SharpShare.Storage.Filter {
    public class FilteredStorageContainer : FilteredStorageItem, IStorageContainer {
        internal FilteredStorageContainer(IStorageContainer baseContainer, IStorageFilter filter, IStorageContainer parent)
            : base(baseContainer, filter, parent) {
            this.Contents = new FilteredStorageLookup(this);
        }

        public new IStorageContainer BaseItem { get { return (IStorageContainer)base.BaseItem; } }

        #region IStorageContainer Members

        public IStorageLookup Contents {
            get;
            private set;
        }

        public IStorageFile CreateFile(string name) {
            IStorageFile newFile = this.BaseItem.CreateFile(name);

            if (newFile == null) {
                return null;
            }

            return FilteredStorageFile.Create(newFile, this.Filter, this);
        }

        public IStorageContainer CreateContainer(string name) {
            IStorageContainer newContainer = this.BaseItem.CreateContainer(name);

            if (newContainer == null) {
                return null;
            }

            return FilteredStorageContainer.Create(newContainer, this.Filter, this);
        }

        #endregion

        #region ICastable<IStorageProvider> Members

        IStorageProvider ICastable<IStorageProvider>.TryCast() {
            return (this as IStorageProvider);
        }

        #endregion

        internal static FilteredStorageContainer Create(IStorageContainer baseContainer, IStorageFilter filter, IStorageContainer parent) {
            return ObjectCache<FilteredStorageContainer>
                .ByKey<Tuple<IStorageContainer, IStorageFilter, IStorageContainer>>
                    .GetOrCreate(
                        Tuple.Create(baseContainer, filter, parent),
                        k => new FilteredStorageContainer(baseContainer, filter, parent));
        }
    }
}
